<?php
session_start();
require_once __DIR__ . '/../bootstrap.php';

use App\Models\Product;
use App\Models\Unit;
use App\Models\Category;
use App\Models\Branch;

if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    header("Location: login.php");
    exit;
}

$productModel = new Product();
$unitModel = new Unit();
$categoryModel = new Category();
$branchModel = new Branch();

$units = $unitModel->getAllUnits();
$categories = $categoryModel->getAllCategories();
$branches = $branchModel->getAllBranches();

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        'product_name' => trim($_POST['product_name'] ?? ''),
        'unit_id' => $_POST['unit_id'] ?: null,
        'wholesale_price' => floatval($_POST['wholesale_price'] ?? 0),
        'retail_price' => floatval($_POST['retail_price'] ?? 0),
        'barcode' => trim($_POST['barcode'] ?? null),
        'description' => trim($_POST['description'] ?? ''),
        'category_id' => $_POST['category_id'] ?: null,
        'stock_quantity' => intval($_POST['stock_quantity'] ?? 0),
        'expiry_date' => $_POST['expiry_date'] ?: null,
        'batch_number' => trim($_POST['batch_number'] ?? ''),
        'branch_id' => $_POST['branch_id'] ?: null,
        'is_pharma' => isset($_POST['is_pharma']) ? 1 : 0
    ];

    if ($data['product_name'] === '') {
        $errors[] = "Product name is required.";
    }
    if ($data['retail_price'] <= 0) {
        $errors[] = "Retail price must be greater than zero.";
    }

    if (empty($errors)) {
        $insertedId = $productModel->create($data);
        if ($insertedId !== false) {
            $success = "Product added successfully.";
            // Clear form
            $data = [];
        } else {
            $errors[] = "Failed to add product.";
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Add Product - Super Market POS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container mt-4">
    <a href="products.php" class="btn btn-secondary mb-3">← Back to Products</a>
    <h1>Add Product</h1>

    <?php if ($success): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <?php if ($errors): ?>
    <div class="alert alert-danger">
        <ul>
            <?php foreach ($errors as $e): ?>
            <li><?= htmlspecialchars($e) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>

    <form method="post" action="">
        <div class="mb-3">
            <label for="product_name" class="form-label">Product Name *</label>
            <input type="text" name="product_name" id="product_name" class="form-control" required value="<?= htmlspecialchars($data['product_name'] ?? '') ?>">
        </div>

        <div class="mb-3">
            <label for="unit_id" class="form-label">Unit</label>
            <select name="unit_id" id="unit_id" class="form-select">
                <option value="">Select Unit</option>
                <?php foreach ($units as $unit): ?>
                <option value="<?= $unit['unit_id'] ?>" <?= (isset($data['unit_id']) && $data['unit_id'] == $unit['unit_id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($unit['unit_name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="mb-3 row">
            <div class="col">
                <label for="wholesale_price" class="form-label">Wholesale Price</label>
                <input type="number" step="0.01" name="wholesale_price" id="wholesale_price" class="form-control" value="<?= htmlspecialchars($data['wholesale_price'] ?? '0.00') ?>">
            </div>
            <div class="col">
                <label for="retail_price" class="form-label">Retail Price *</label>
                <input type="number" step="0.01" name="retail_price" id="retail_price" class="form-control" required value="<?= htmlspecialchars($data['retail_price'] ?? '') ?>">
            </div>
        </div>

        <div class="mb-3">
            <label for="barcode" class="form-label">Barcode</label>
            <input type="text" name="barcode" id="barcode" class="form-control" value="<?= htmlspecialchars($data['barcode'] ?? '') ?>">
        </div>

        <div class="mb-3">
            <label for="description" class="form-label">Description</label>
            <textarea name="description" id="description" class="form-control"><?= htmlspecialchars($data['description'] ?? '') ?></textarea>
        </div>

        <div class="mb-3">
            <label for="category_id" class="form-label">Category</label>
            <select name="category_id" id="category_id" class="form-select">
                <option value="">Select Category</option>
                <?php foreach ($categories as $category): ?>
                <option value="<?= $category['category_id'] ?>" <?= (isset($data['category_id']) && $data['category_id'] == $category['category_id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($category['category_name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="mb-3">
            <label for="stock_quantity" class="form-label">Stock Quantity</label>
            <input type="number" name="stock_quantity" id="stock_quantity" class="form-control" value="<?= htmlspecialchars($data['stock_quantity'] ?? '0') ?>">
        </div>

        <div class="mb-3 row">
            <div class="col">
                <label for="expiry_date" class="form-label">Expiry Date</label>
                <input type="date" name="expiry_date" id="expiry_date" class="form-control" value="<?= htmlspecialchars($data['expiry_date'] ?? '') ?>">
            </div>
            <div class="col">
                <label for="batch_number" class="form-label">Batch Number</label>
                <input type="text" name="batch_number" id="batch_number" class="form-control" value="<?= htmlspecialchars($data['batch_number'] ?? '') ?>">
            </div>
        </div>

        <div class="mb-3">
            <label for="branch_id" class="form-label">Branch</label>
            <select name="branch_id" id="branch_id" class="form-select">
                <option value="">Select Branch</option>
                <?php foreach ($branches as $branch): ?>
                <option value="<?= $branch['branch_id'] ?>" <?= (isset($data['branch_id']) && $data['branch_id'] == $branch['branch_id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($branch['branch_name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-check mb-3">
            <input type="checkbox" name="is_pharma" id="is_pharma" class="form-check-input" <?= !empty($data['is_pharma']) ? 'checked' : '' ?>>
            <label for="is_pharma" class="form-check-label">Is Pharmaceutical</label>
        </div>

        <button type="submit" class="btn btn-success">Add Product</button>
    </form>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
